package org.example.volunteerend.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.example.volunteerend.dto.ServiceRecordRequest;
import org.example.volunteerend.entity.ServiceRecord;
import org.example.volunteerend.entity.User;
import org.example.volunteerend.entity.VolunteerProject;
import org.example.volunteerend.mapper.ServiceRecordMapper;
import org.example.volunteerend.mapper.UserMapper;
import org.example.volunteerend.mapper.VolunteerProjectMapper;
import org.example.volunteerend.service.ServiceRecordService;
import org.example.volunteerend.utils.AliOssUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class ServiceRecordServiceImpl implements ServiceRecordService {

    private final ServiceRecordMapper serviceRecordMapper;
    private final VolunteerProjectMapper volunteerProjectMapper;
    private final UserMapper userMapper;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional
    public Integer addServiceRecord(ServiceRecordRequest request) {
        // 校验请求参数
        if (request.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (request.getProjectId() == null) {
            throw new IllegalArgumentException("项目ID不能为空");
        }
        if (request.getServiceDate() == null) {
            throw new IllegalArgumentException("服务日期不能为空");
        }
        if (request.getServiceHours() == null || request.getServiceHours().doubleValue() <= 0) {
            throw new IllegalArgumentException("服务时长必须大于0");
        }
        
        // 校验用户和项目是否存在
        User user = userMapper.findById(request.getUserId());
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        VolunteerProject project = volunteerProjectMapper.findById(request.getProjectId());
        if (project == null) {
            throw new IllegalArgumentException("项目不存在");
        }
        
        // 创建服务记录
        ServiceRecord record = new ServiceRecord();
        record.setUserId(request.getUserId());
        record.setProjectId(request.getProjectId());
        record.setServiceDate(request.getServiceDate());
        record.setServiceHours(request.getServiceHours());
        record.setDescription(request.getDescription());
        record.setProofImages(request.getProofImages() != null ? request.getProofImages() : new ArrayList<>());
        
        // 转换证明图片列表为JSON
        String proofImagesJson;
        try {
            proofImagesJson = objectMapper.writeValueAsString(record.getProofImages());
        } catch (JsonProcessingException e) {
            throw new RuntimeException("证明图片列表转换JSON失败", e);
        }
        
        // 插入服务记录
        serviceRecordMapper.insert(record, proofImagesJson);
        
        return record.getRecordId();
    }

    @Override
    public List<String> uploadProofImages(List<MultipartFile> imageFiles) throws Exception {
        if (imageFiles == null || imageFiles.isEmpty()) {
            throw new IllegalArgumentException("证明图片不能为空");
        }
        
        List<String> imageUrls = new ArrayList<>();
        for (MultipartFile imageFile : imageFiles) {
            if (imageFile != null && !imageFile.isEmpty()) {
                // 获取文件扩展名
                String originalFilename = imageFile.getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                
                // 构建OSS存储路径
                String filename = "service-records/proofs/" + UUID.randomUUID().toString() + extension;
                
                // 上传到阿里云OSS
                String imageUrl = AliOssUtil.uploadFile(filename, imageFile.getInputStream());
                
                // 添加到图片URL列表
                imageUrls.add(imageUrl);
            }
        }
        
        return imageUrls;
    }

    @Override
    public ServiceRecord getServiceRecordDetail(Integer recordId) {
        if (recordId == null) {
            throw new IllegalArgumentException("记录ID不能为空");
        }
        
        ServiceRecord record = serviceRecordMapper.findById(recordId);
        if (record == null) {
            throw new IllegalArgumentException("服务记录不存在");
        }
        
        // 解析证明图片JSON
        String proofImagesJson = serviceRecordMapper.findProofImagesByRecordId(recordId);
        if (proofImagesJson != null && !proofImagesJson.isEmpty()) {
            try {
                List<String> proofImages = objectMapper.readValue(proofImagesJson, new TypeReference<List<String>>() {});
                record.setProofImages(proofImages);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("证明图片JSON解析失败", e);
            }
        } else {
            record.setProofImages(new ArrayList<>());
        }
        
        return record;
    }

    @Override
    public List<ServiceRecord> getUserServiceRecords(Integer userId) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        
        return serviceRecordMapper.findByUserId(userId);
    }
} 